<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>SSE 实时翻译</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 30px;
        }
        label, input, textarea, select {
            display: block;
            margin-bottom: 15px;
            width: 100%;
            max-width: 600px;
        }
        #output {
            white-space: pre-wrap;
            border: 1px solid #ccc;
            padding: 15px;
            margin-top: 20px;
            background: #f9f9f9;
            max-width: 600px;
        }
    </style>
</head>
<body>

<h2>实时翻译（SSE）</h2>

<form id="translateForm">
    <label for="language_src">源语言（可选）：</label>
    <input type="text" id="language_src" name="language_src" placeholder="例如 中文">

    <label for="language_dst">目标语言：</label>
    <input type="text" id="language_dst" name="language_dst" placeholder="例如 英文" required>

    <label for="text">需要翻译的文本：</label>
    <textarea id="text" name="text" rows="5" placeholder="请输入要翻译的内容" required></textarea>

    <button type="submit">开始翻译</button>
</form>

<h3>翻译结果：</h3>
<div id="output">（等待翻译输出...）</div>

<script>
document.getElementById("translateForm").addEventListener("submit", async function (e) {
    e.preventDefault();

    const languageSrc = document.getElementById("language_src").value.trim();
    const languageDst = document.getElementById("language_dst").value.trim();
    const text = document.getElementById("text").value.trim();

    if (!languageDst || !text) {
        alert("目标语言和翻译文本不能为空！");
        return;
    }

    const outputDiv = document.getElementById("output");
    outputDiv.textContent = "";

    // 关闭前一个连接
    if (window.currentEventSource) {
        window.currentEventSource.close();
    }

    // 发起 POST 请求初始化 SSE
    const response = await fetch("http://101.201.118.111:11014/translate_stream", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            text: text,
            language_dst: languageDst,
            language_src: languageSrc
        })
    });

    if (!response.ok) {
        outputDiv.textContent = "请求失败: " + response.statusText;
        return;
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");

    let buffer = "";
    while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        // 处理 SSE 消息（简单解析）
        const lines = buffer.split("\n");
        buffer = lines.pop(); // 可能是 incomplete 的最后一行
        for (const line of lines) {
            if (line.startsWith("data:")) {
                const data = line.slice(5).trim();
                if (data === "[[END]]") {
                    return;
                }
                outputDiv.textContent += data+" ";
            }
        }
    }
});
</script>


</body>
</html>
